﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace Jinndev.GameKit {

    /// <summary>
    /// 物品图标默认实现
    /// </summary>
    public class ItemIcon : BaseUIBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler, IItemUI {

        public static string PATH = "Jinndev/Prefab/UI/ItemIcon";
        public static float DesignHeight = 100;

        public delegate void SetIconDelegate(RawImage rawImage, int id);
        public static SetIconDelegate SetIcon;

        public System.Action<IItemUI, PointerEventData> onPointerClick;

        /// <summary>
        /// 当前指针事件处理器，由使用者传入
        /// </summary>
        public PointerHandler pointerHandler;

        [Header("组件")]
        public GameObject background;
        public RawImage imageIcon;
        public GameObject objSelected;
        public GameObject objIndex;
        public GameObject objNum;
        public Text textIndex;
        public Text textNum;

        protected Item _item;
        protected int index = -1;

        /// <summary>
        /// 图标设置
        /// </summary>
        public ItemIconSetting Setting { get; protected set; }
        /// <summary>
        /// 指针是否进入/悬浮
        /// </summary>
        public bool PointerEntered { get; protected set; }
        /// <summary>
        /// 指针知否按下
        /// </summary>
        public bool PointerDown { get; protected set; }
        /// <summary>
        /// 当前是否被选中
        /// </summary>
        public bool Selected { get; protected set; }

        protected int indexFontSize; // 索引字体字号
        protected int numFontSize; // 数量字体字号

        protected virtual void Awake() {
            Index = -1;
            objSelected.SetActive(false);

            indexFontSize = textIndex.fontSize;
            numFontSize = textNum.fontSize;
        }

        protected virtual IEnumerator Start() {
            // 根据缩放，适配字号大小
            float scale = GetComponent<RectTransform>().rect.size.y / DesignHeight;
            if (scale != 1) {
                textIndex.fontSize = Mathf.CeilToInt(indexFontSize * scale);
                textNum.fontSize = Mathf.CeilToInt(numFontSize * scale);
            }
            else {
                yield return new WaitForEndOfFrame();
                scale = GetComponent<RectTransform>().rect.size.y / DesignHeight;
                if (scale != 1) {
                    textIndex.fontSize = Mathf.CeilToInt(indexFontSize * scale);
                    textNum.fontSize = Mathf.CeilToInt(numFontSize * scale);
                }
            }
        }

        protected virtual void OnDestroy() {
            if (!IsQuitting && PointerEntered) {
                pointerHandler?.Exit(Index, Item);
            }
            pointerHandler = null;
        }

        /// <summary>
        /// 初始化图标
        /// </summary>
        /// <param name="setting">图标设置</param>
        /// <param name="pointerHandler">指针输入操作处理器</param>
        /// <param name="onPointerClick">指针点击回调</param>
        public virtual void Init(ItemIconSetting setting, PointerHandler pointerHandler = null, System.Action<IItemUI, PointerEventData> onPointerClick = null) {
            Setting = setting;
            this.pointerHandler = pointerHandler;
            this.onPointerClick = onPointerClick;

            if (background != null) {
                background.SetActive(Setting.showBg);
            }
            if (objIndex != null) {
                objIndex.SetActive(Setting.showIndex);
            }
            if (objNum != null) {
                objNum.SetActive((Setting.showNum || Setting.showMaxNum) && Item.max >= 0);
            }
        }

        public virtual void Set(Item item, int index, bool selected = false) {
            Item = item;
            Index = index;
            SetSelected(selected);
        }

        public int Index {
            get {
                return index;
            }
            set {
                index = value;
                if (Setting.showIndex) {
                    textIndex.text = (Setting.indexOffset + index).ToString();
                }
            }
        }

        /// <summary>
        /// 设置/获得当前Item
        /// </summary>
        public Item Item {
            get {
                return _item;
            }
            set {
                SetItem(value);
            }
        }

        /// <summary>
        /// 设置当前Item
        /// </summary>
        /// <param name="item"></param>
        /// <returns>是否发生了变化</returns>
        public virtual bool SetItem(Item item) {
            if (item.IsEmptyID()) {
                imageIcon.texture = null;
                objNum.SetActive(false);
            }
            else {
                if (_item.id != item.id) {
                    if (SetIcon != null) {
                        SetIcon.Invoke(imageIcon, item.id);
                    }
                    else {
                        Debug.LogError("ItemIcon.SetIcon not set");
                    }
                }

                bool showNum = (Setting.showNum || Setting.showMaxNum) && item.max >= 0;
                objNum.SetActive(showNum);

                if (showNum && (_item.num != item.num || _item.max != item.max)) {
                    if (Setting.showNum && Setting.showMaxNum) {
                        textNum.text = $"{item.num}/{item.max}";
                    }
                    else if (Setting.showNum) {
                        textNum.text = GetNumText(item);
                    }
                    else if (Setting.showMaxNum) {
                        textNum.text = item.max.ToString();
                    }
                }
            }

            if (item.Equals(_item)) {
                return false;
            }
            _item = item;

            // 如果指针悬停，则需要更新悬浮窗信息
            if (PointerEntered) {
                if (Item.id != Item.EmptyID) {
                    pointerHandler?.Enter(Index, Item, transform as RectTransform);
                }
                else {
                    pointerHandler?.Exit(Index, Item);
                }
            }
            return true;
        }

        protected string GetNumText(Item item) {
            return string.IsNullOrWhiteSpace(Setting.numFormat) ? item.num.ToString() : string.Format(Setting.numFormat, item.num);
        }

        public virtual void SetSelected(bool selected) {
            Selected = selected;
            if (Setting.showSelected) {
                objSelected.SetActive(selected);
            }
        }

        /// <summary>
        /// 设置图标浮动时的样式
        /// </summary>
        public virtual void EnableFloatingStyle() {
            if (background != null) {
                background.SetActive(false);
            }
        }

        /// <summary>
        /// UI点击事件，区别于OnClick
        /// </summary>
        public virtual void OnPointerClick(PointerEventData eventData) {
            onPointerClick?.Invoke(this, eventData);
        }

        /// <summary>
        /// 指针进入事件
        /// </summary>
        public virtual void OnPointerEnter(PointerEventData eventData) {
            PointerEntered = true;
            if (Item.id != Item.EmptyID) {
                pointerHandler?.Enter(Index, Item, transform as RectTransform);
            }
        }

        /// <summary>
        /// 指针离开事件
        /// </summary>
        public virtual void OnPointerExit(PointerEventData eventData) {
            PointerEntered = false;
            pointerHandler?.Exit(Index, Item);
        }

    }

}